package com.yjs.app.trade.web.controller.interceptor;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yjs.app.trade.core.util.JedisUtil;
import com.yjs.app.trade.entity.base.SysConstant;
import com.yjs.app.trade.web.controller.base.BaseController;
import com.yjs.app.trade.web.controller.base.util.Result;

import net.sf.json.JSONObject;

public class AuthenticationInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
//		TokenThreadLocal.remove("token");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials","true");
		String token = request.getHeader(BaseController.userToken);
		String result = "";
		if (token != null && JedisUtil.get(token) != null) {
			JSONObject jsonObject = JSONObject.fromObject(JedisUtil.get(token));
			if (JSONObject.fromObject(jsonObject.get("allAttribute")).get("PASSPORT_ID") != null) {
				JedisUtil.setex(token, jsonObject.toString(), 30 * 60);
//				TokenThreadLocal.setValue(AuthorityFilterAop.TOKEN, token);
				List<JSONObject> typesInfo = JSONObject.fromObject(JedisUtil.get(token)).getJSONArray("appNatures");
				List<String> types = new ArrayList<String>();
				for (JSONObject json : typesInfo) {
					types.add(json.getString("appNatureId"));
				}
				Map<String, Integer> autMap =  AuthenticationUtil.getUserAuts(types, JSONObject.fromObject(JedisUtil.get(token)).getJSONArray("userPermissionId"));
				String autType = request.getHeader(BaseController.autType);
				if (autType != null && autMap.get(autType) != null && autMap.get(autType) == 1) {
					return true;
				}
			} 
			result = Result.cfail(SysConstant.ErrorCode.NO_AUT,"没有权限");
		} else {
			result = Result.cfail(SysConstant.ErrorCode.NO_LOGIN,"请先登录");
		}
		PrintWriter writer = response.getWriter();
		writer.print(result);
		writer.close();
		return false;
	}

}
